//
//  MTWithdrawController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/6.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory

import Moya
import Result
import RxSwift
import RxCocoa
import YPNavigationBarTransition

class MTWithdrawController: BaseViewController {
    
    /// UserApi
    private lazy var user_provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    var model: MineWithdrawModel?
    
    @objc
    enum SettingType: Int {
        case ratio = 0
        case record
        case auth
        case alipay
        case bankCard
        
        /// 标题
        var title: String {
            switch self {
            case .ratio:
                return "当前提现比例"
            case .record:
                return "提现记录"
            case .auth:
                return "实名认证"
            case .alipay:
                return "支付宝绑定"
            case .bankCard:
                return "银行卡绑定"
            }
        }
        
        /// 展示
        var detail: Any {
            switch self {
            case .ratio:
                return "0%"
            case .record:
                return "已结算0元"
            case .auth:
                return "未认证"
            case .alipay:
                return "未绑定"
            case .bankCard:
                return "未绑定"
            }
        }
        
        /// 是否展示 > 图标
        var isIndicatorNeeded: Bool {
            return true
        }
    }
    
    var displayType: [SettingType] = [.ratio,.record,.auth]
    
    lazy var tableView: UITableView = {
        let tv = UITableView(frame: self.view.bounds, style: .grouped)
        tv.delegate = self
        tv.dataSource = self
        tv.showsVerticalScrollIndicator = false
        tv.backgroundColor = UIColor(hex: 0xf6f6f6)
        tv.register(MineSettingTableViewCell.self, forCellReuseIdentifier: String(describing: MineSettingTableViewCell.self))
        return tv
    }()
    
    lazy var checkoutButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("结算", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.clipsToBounds = true
        btn.addTarget(self, action: #selector(withdrawViewController(didClickCheckoutButton:)), for: .touchUpInside)
        return btn
    }()
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MTWithdrawController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadData()
        initializeUI()
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MTWithdrawController {
    
    private func initializeUI() {
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        navigationItem.title = "提现"
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 56, height: 20))
        button.setTitle("联系客服", for: .normal)
        button.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        button.titleLabel?.font = PingFangSCMediumFont(14)
        button.addTarget(self, action: #selector(withdrawViewController(didClickContactButton:)), for: .touchUpInside)
        let rightBarButton = UIBarButtonItem(customView: button)
        self.navigationItem.rightBarButtonItem = rightBarButton
        
        view.addSubview(tableView)
        view.addSubview(checkoutButton)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        checkoutButton.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(50)
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 20)
        }
    }
    
    private func loadData() {
        user_provider.rx.requestResult(.withdrawSummary).subscribe(onNext: { [weak self] (result: Result<MineWithdrawResponseModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if response.code == 200, let model = response.result {
//                    weakself.presentWithdrawAlert(with: "提现", message: "您的\(model.ticketAmount)点券将提现成\n\(model.rmbAmount)人民币，是否提现？") {
//                        weakself.applyWithdraw(with: model)
//                    }
                    weakself.model = model
                    weakself.tableView.reloadData()
                } else {
                    AlertManager.presentAlertView(message: response.message ?? "申请失败")
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: disposeBag)

    }
    
    private func authStatus(status: Int) -> String {
        switch status {
        case -1:
            return "未认证"
        case 0:
            return "审核中"
        case 1:
            return "认证成功"
        case 2:
            return "重新认证"
        default:
            return "未认证"
        }
    }
    
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTWithdrawController {
    
    private func withdrawViewController(didClickContactButton sender: UIButton) {
        if let un = UserCenter.default.customerUserName {
            JMSGConversation.createSingleConversation(withUsername: un) { [weak self] (conversation, error) in
                guard let weakSelf = self else { return }
                if error == nil, conversation != nil {
                    if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[1] as? BaseNavController {
                        nav.selectCategory()
                        
                        DispatchQueue.main.after(0.25) {
                            let conv: JMSGConversation = conversation as! JMSGConversation
                            nav.pushViewController(JCChatViewController(conversation: conv), animated: true)
                        }
                        
                        DispatchQueue.main.after(1, execute: {
                            weakSelf.navigationController?.popToRootViewController(animated: false)
                        })
                    }
                }
            }
        }
    }
    
    private func withdrawViewController(didClickCheckoutButton sender: UIButton) {
        if model?.status == 1 {
            let vc = MTCheckoutController()
            vc.model = self.model
            self.navigationController?.pushViewController(vc, animated: true)
        } else {
            AlertManager.presentAlertView(message: "实名认证成功才能提现")
        }
    }
    
}

// MARK: ------------------------------------ 所有代理 ----------------------------------------
// MARK: ------------------------------------ UITableViewDelegate ----------------------------------------
extension MTWithdrawController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let t = displayType[indexPath.row]
        switch t {
        case .ratio:
            let vc: MTWithdrawTaskListController = MTWithdrawTaskListController()
            vc.rate = model?.withdrawRate ?? 0
            navigationController?.pushViewController(vc, animated: true)
            break
        case .record:
            navigationController?.pushViewController(MTWithdrawRecordController(), animated: true)
            break
        case .auth:
            if model?.status == -1 || model?.status == 2 {
                let vc = MTCertificationController()
                vc.completionHandler = {() -> Void in
                    self.loadData()
                }
                navigationController?.pushViewController(vc, animated: true)
            } else if model?.status == 0 {
                AlertManager.presentAlertView(message: "认证审核中，请耐心等待")
            }
            break
        default:
            break
            
        }

    }
    
}

// MARK: ------------------------------------ UITableViewDataSource ----------------------------------------
extension MTWithdrawController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return displayType.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MineSettingTableViewCell.self), for: indexPath) as? MineSettingTableViewCell else {
            return tableView.dequeueReusableCell(withIdentifier: String(describing: MineSettingTableViewCell.self), for: indexPath)
        }
        let type = self.displayType[indexPath.row]
        switch type {
        case .ratio:
            cell.detailStr = "\(model?.withdrawRate ?? 0)%"
            break
        case .record:
            cell.detailStr = "已结算\(model?.withDrawMoney ?? 0)元"
            break
        case .auth:
            cell.detailStr = authStatus(status: model?.status ?? 0)
            break
        default:
            break
            
        }
        cell.wdSettingType = self.displayType[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 90
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0x2f2f2f)
        let label = UILabel()
        label.text = "最高可提现"
        label.textColor = .white
        label.font = PingFangSCMediumFont(14)
        view.addSubview(label)
        let money = UILabel()
        money.text = "\(self.model?.enableMoney ?? 0)元"
        money.textColor = UIColor(hex:0xffc000)
        money.font = PingFangSCSemiboldFont(20)
        money.textAlignment = .right
        view.addSubview(money)
        
        label.snp.makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.left.equalTo(view).offset(15)
            
        }
        
        money.snp.makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.right.equalTo(view).offset(-15)
            make.width.equalTo(300)
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
